unit bootthread;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, ComCtrls, ExtCtrls, StdCtrls, IdHTTP, jpeg, math, XMLDoc, XMLIntf,
  QControls,strutils,IdComponent, IdTCPConnection,IdTCPClient, Sockets, superobject;
type
  Tbootthread = class(TThread)
  private
    { Private declarations }
  protected
    procedure Execute; override;
  public
    constructor create;
    procedure uploadThreadnum;           //
  end;

implementation

uses html;
{ Important: Methods and properties of objects in visual components can only be
  used in a method called using Synchronize, for example,

      Synchronize(uploadThreadnum);

  and UpdateCaption could look like,

    procedure THttpThread.UpdateCaption;
    begin
      Form1.Caption := 'Updated in a thread';
    end; }

{ THttpThread }
procedure Tbootthread.uploadThreadnum;
begin
          
end;
procedure Tbootthread.Execute;
var
  state:integer;
  pointer:integer;
  i:Integer;
  strs,msgids:tstringlist;
  TCPClient: TidTCPClient;
  strhost:string;
  intport:integer;
  strid :string;
  msg,rec:string;
  curpc :integer;
  aJson,asrc: ISuperObject;
  trytimes:integer;
  succeed:boolean;
  deleytime:integer;
  sstrs:tstringlist;
  substrs:tstringlist;
  j,k:integer;
  cmd:string;
  ress:integer;
  reclen:integer;
  swver:integer;
  hwver:integer;
  devtype:integer;
  sysinfos:tstringlist;
  noallowed:boolean;
  xnum,ynum:integer;
  countx:integer;
  downloadtype:string;
  checkver:boolean;
  idhttp:tidhttp;
  ishttp:boolean;
  httpurl:string;
  enableup:boolean;
begin
  { Place thread code here }
  strs:=tstringlist.create;
  msgids:=tstringlist.create;
  TCPClient := tidtcpclient.Create(nil);
  downloadtype :=  FrmBootloader.downloadtype;
  while not(terminated) do
  begin
      strs.Clear;
      msgids.Clear;
      noallowed := false;
      swver:=0;
      hwver:=0;
      devtype:=0;
      EnterCriticalSection(disMute);

      state := FrmBootloader.state;
      pointer := FrmBootLoader.pointer;
      strhost := FrmBootLoader.txtHost.Text;
      intport := strtoint(frmBootLoader.txtPort.text);
      strid := frmbootloader.txtdstid.text;
      downloadtype :=  FrmBootloader.downloadtype;
      ishttp := FrmBootloader.ishttp;
      httpurl := FrmBootloader.httpurl;
      if(state = 1) then
      begin
          FrmBootloader.msgLogs.lines.Clear;
          for i:= 0 to FrmBootLoader.strcommands.Count - 1 do
          begin
              strs.Add(FrmBootLoader.strcommands[i]);
              msgids.add(frmbootloader.msgids[i]);
          end;
      end;
      LeaveCriticalSection(disMute);
      if(state = 1) then
      begin
          if(ishttp = true) then
          begin
            enableup := true;
          end
          else
          begin
              TCPClient.Host := strhost;
              tcpclient.Port := intport;
              tcpclient.ConnectTimeout := 4000;
              try
                tcpclient.Connect;
              except
              end;
              if(tcpclient.Connected) then
              begin
                enableup := true;
              end;
          end;
          if(enableup) then
          begin
              curpc := 0;
              trytimes := 0;
              while(curpc < strs.count) do
              begin
                 msg := strs[curpc];

                 succeed := false;
                 rec := '';
                 countx := 0;
                 if(ishttp) then
                 begin
                   idhttp:=tidhttp.Create();
                   idhttp.ConnectTimeout := 2000;
                   idhttp.ReadTimeout := 2000;
                   rec := '';
                   try
                    rec := idhttp.Get(httpurl + msg);
                    except
                      rec := '';
                    end;
                   freeandnil(idhttp);
                 end
                 else
                 begin
                     deleytime := 100;
                     msg := msg + #13;
                     tcpclient.IOHandler.write(msg);
                     if(curpc = 0) then
                     begin

                        deleytime := 100;
                     end;
                     while(rec = '') and (countx <= 30) do
                     begin
                         sleep(deleytime);
                         inc(countx);
                         //tcpclient.IOHandler.Recv(rec, reclen);
                         rec := tcpclient.IOHandler.ReadLn(#13,500,65535);   //
                     end;
                 end;
                 if(rec <> '') then
                 begin
                    try
                      aJson:=FrmBootLoader.getCMD(rec, ishttp);
                      checkver := false;
                      if(downloadtype <> 'wifi') and (curpc = 0) then
                      begin
                        checkver := true;
                      end
                      else
                      begin
                        noallowed := false;
                      end;
                      if(checkver) then
                      begin
                            if(aJson['sysf']<> nil) then//
                            begin
                              sysinfos:=tstringlist.create;
                              sysinfos.Delimiter := ',';
                              sysinfos.DelimitedText := aJson['sysf'].AsString;
                              if(sysinfos.Count >= 6) then
                              begin
                                xnum := (strtoint('$'+sysinfos[0]) and $ff00) shr 8;
                                ynum := (strtoint('$'+sysinfos[0]) and $ff);
                                swver := strtoint('$'+sysinfos[3]);
                                hwver := strtoint('$'+sysinfos[4]);
                                devtype := (strtoint('$'+sysinfos[5]) and $ff00) shr 8;
                                succeed:= true;
                                if(frmbootloader.validDevice(swver,hwver,devtype, xnum, ynum))then
                                begin
                                  noallowed := false;
                                end
                                else
                                begin
                                  noallowed := true;
                                end;
                              end;
                              freeandnil(sysinfos);
                            end;

                      end
                      else
                      begin
                          if(aJson['binary']<> nil)
                            and (aJson['binary']<>nil)
                            and (aJson['msgid']<>nil)
                            and (aJson['t']<> nil)  then
                          begin
                              cmd := ajson['binary'].AsString;
                              EnterCriticalSection(disMute);
                              frmbootloader.refreshStatus(cmd, strtoint(msgids[curpc]));
                              LeaveCriticalSection(disMute);
                              ress := strtoint(ansimidstr(cmd, 3, 2));
                              //showmessage(aJson['msgid'].Asstring+' '+ msgids[curpc]);
                              if(downloadtype = 'wifi') then
                              begin
                                if(aJson['msgid'].AsInteger = strtoint(msgids[curpc]))
                                  and (aJson['t'].asstring = 'ota')
                                   and (ress = 1) then
                                begin
                                  succeed := true;
                                end;
                              end
                              else
                              begin
                                if(aJson['msgid'].AsInteger = strtoint(msgids[curpc]))
                                  and (aJson['t'].asstring = 'binary')
                                   and (ress = 1) then
                                begin
                                  succeed := true;
                                end;
                             end;
                          end;
                      end;
                    except
                    end;

                 end;
                 EnterCriticalSection(disMute);     //
                 FrmBootloader.msgLogs.lines.add('send='+inttostr(curpc)+',total='+inttostr(strs.Count)+',recmsg='+rec);
                 LeaveCriticalSection(disMute);
                 if(succeed) then
                 begin
                   inc(curpc);
                   if(curpc = 1) then
                   begin
                    sleep(1000);
                   end
                   else
                   begin
                    sleep(20);
                   end;
                   trytimes := 0;
                   if(noallowed = true) then
                   begin
                     break;
                   end;
                 end
                 else
                 begin
                    inc(trytimes);
                    if(trytimes > 3) then
                    begin
                      break;
                    end;
                    sleep(2000);
                 end;


              end;
          end;
           EnterCriticalSection(disMute);
           FrmBootloader.msgLogs.lines.add('finish');
           FrmBootloader.state := 0;
           LeaveCriticalSection(disMute);
           if(ishttp = false) then
           begin
            tcpclient.Disconnect;
           end;
          suspend();
      end;
  end;
  freeandnil(strs);
  freeandnil(TCPClient);
  freeandnil(msgids);
end;
constructor Tbootthread.create;
begin
  inherited create(true);
  FreeOnTerminate := true;

end;

end.
